package com.atmilan.quartz.utils.product;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.DelloglioXmlSaxHandler;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.bellettini.BellettiniProductResDTO;
import com.atmilan.quartz.model.dto.delloglio.DelloglioProductResDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class DelloglioProductUtil {

    @Value("${delloglio.url}")
    private String delloglioUrl;

    /**
     * 获取Delloglio商品列表
     * @return
     */
    public DelloglioProductResDTO getDelloglioProductList() throws IOException {
        DelloglioProductResDTO delloglioProductResDTO = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            //1)    创建SAXParserFactory的对象
            SAXParserFactory spf=SAXParserFactory.newInstance();
            //2)    创建SAXParser对象 (解析器)
            SAXParser parser=spf.newSAXParser();
            URL url = new URL(delloglioUrl);
            conn=(HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(1000 * 60 * 60 * 6);
            conn.setReadTimeout(1000 * 60 * 60 * 6);
            inputStream = conn.getInputStream();
            DelloglioXmlSaxHandler xmlSaxHandler = new DelloglioXmlSaxHandler();
            parser.parse(inputStream, xmlSaxHandler);
            delloglioProductResDTO = xmlSaxHandler.getDelloglioProductResDTO();
        } catch (Exception e) {
            log.error("---------拉取Delloglio商品列表失败{}------------", e.getMessage(),e);

        }finally {
            if(inputStream != null){
                inputStream.close();
            }
            if(conn != null){
                conn.disconnect();
            }
        }
        return delloglioProductResDTO;
    }

}
